package com.qdlc.p2p.biz.task.impl;

import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;

import com.qdlc.p2p.biz.service.TppInvestService;
import com.qdlc.p2p.biz.task.AbstractLoanTask;
import com.qdlc.p2p.biz.task.JobQueue;
import com.qdlc.p2p.biz.task.ValueEvent;
import com.qdlc.p2p.common.constant.Global;
import com.qdlc.p2p.common.constant.Summary;
import com.qdlc.p2p.common.exception.BusinessException;
import com.qdlc.p2p.common.util.BeanUtil;
import com.qdlc.p2p.dal.model.TppModel;

/**
 * 自动调度任务业务队列
 * @author ygw
 * @version 1.0
 * @date 2016年3月7日 下午5:00:29
 */
public class TppDispatchTask extends AbstractLoanTask {

	private Logger logger = Logger.getLogger(TppDispatchTask.class);

	public TppDispatchTask() {
		super();
		task.setName("TppDispatchTask.Task");
	}

	@SuppressWarnings("unchecked")
	@Override
	public void doLoan() {
		
		// 延时5分钟处理，防止金额未到账
		try {
            Thread.currentThread().sleep(5*60*1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
		
		TppInvestService tppInvestService = (TppInvestService) BeanUtil.getBean("tppInvestService");
		JobQueue<ValueEvent> queue = JobQueue.getTppDispatchInstance();
		while (!queue.isEmpty()) {
			ValueEvent event = queue.peek();
			if (event != null) {
				String result = "success";
				try {
					if ("tppDispatch".equals(event.getOperate())) {
						TppModel tppModel = event.getTppModel();
						List<TppModel> taskList = new ArrayList<TppModel>();
						logger.info("自动调度处理当前ID:" + tppModel.getId());
						tppModel.setSummary(Summary.getSummaryNameByType(tppModel.getServiceType())+"(补单)");
						taskList.add(tppModel);
						tppInvestService.tppDispatchTask(taskList);
					}
				} catch (Exception e) {
					logger.error(e.getMessage(), e);
					if (e instanceof BusinessException) {// 业务异常，保存业务处理信息
						result = e.getMessage();
					} else {
						result = "系统异常，业务处理失败";
					}
					MailUtil.sendMail("自动调度任务业务队列异常",e);
				} finally {
					queue.remove(event);
				}
				if (event.getResultFlag() != null) {// 在需要保存系统处理信息的地方直接保存进来
					Global.TASK_RESULT_MAP.put(event.getResultFlag(), result);
				}
			}
		}
	}
}
